<?php
// +----------------------------------------------------------------------
// | 无限级树操作类
// +----------------------------------------------------------------------
// | 深圳市君鉴测试仪器租赁有限公司
// +----------------------------------------------------------------------
// | Author: 卓战友 125323228@qq.com
// +----------------------------------------------------------------------

namespace Common\Controller;

class Tree{

    //默认配置
    protected $_config = array(
        'FIELDS'            => array('mid','pid','menu_name','url','ico'),
		'IMGPATH'           => '/ico',
		'ROOTID'            => 0
    );
	protected $data       = array();
	protected $pdata      = array();
	protected $indentArr  = array();
	protected $root_id    = 0;
	protected $layer      = 0;
	
	public $menuStr    = null;

    public function __construct($config='') {
       if(is_array($config))
	   {
			foreach($config as $k=>$v)
			{
				$this->_config[$k] = $v;
			}
	   }
    }
	public function setData($data)
	{
		$fields = $this->_config['FIELDS'];
		if(!is_array($data)) return;
		foreach($data as $a)
		{
			$this->data[$a[$fields[1]]][] = array($a[$fields[0]],$a[$fields[2]],$a[$fields[3]],$a[$fields[4]]);
		}
		foreach($this->data as $k=>$a)
		{
			$this->pdata[] = $k;
		}
	}
	public function chrent_menu($pid=0)
	{
		if(is_array($this->data[$pid]))
		{
			foreach($this->data[$pid] as $k=>$a)
			{
				if($pid==0)
				{
					$this->menuStr .= '<div>';
					$this->menuStr .= '<div class="left_div">';
					$this->menuStr .= '<span style="background:url(' . C('TMPL_PARSE_STRING.__CSS__') . '/ico/' . $a[3] . ') no-repeat 13px 6px;">';
					$this->menuStr .= $a[1] . '</span></div>';
					$this->menuStr .= '<ul title="' . $a[1] . '">';
				}
				else
				{
					$this->menuStr .= '<li id="m' . $a[0] . '" title="' . U($a[2]) . '" class="left_menu_link">' . $a[1] . '</li>';
				}
				if(in_array($a[0],$this->pdata))
				{
					$this->chrent_menu($a[0]);
				}
				if($pid==0)
				{
					$this->menuStr .= '</ul></div>';
				}
			}
		}
	}

	//树形select显示
	public function option($pid=0,$selected='')
	{
		if(is_array($this->data[$pid]))
		{
			$end = end($this->data[$pid]);
			foreach($this->data[$pid] as $a)
			{
				$this->menuStr .= "<option value=\"$a[0]\"";
				if($selected!='' && $selected==$a[0]) $this->menuStr .= " selected";
				$this->menuStr .= ">";
				$this->optionsindent($a[0],$pid);
				$this->menuStr .= " $a[1] ";
				$this->menuStr .= "</option>";
				if(in_array($a[0],$this->pdata))
				{
					$this->option($a[0],$selected);
				}
				array_pop($this->indentArr);
			}
		}
	}
	public function optionsindent($id,$pid)
	{
		foreach($this->indentArr as $a)
		{
			$img = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
			$this->menuStr .= $img;
		}
		$end = end($this->data[$pid]);
		$isend = $end[0]==$id?1:0;
		array_push($this->indentArr,$isend);

	}
}
